const blogRouter = require('./src/router/blogRouter')
const userRouter = require('./src/router/userRouter')
const querystring = require('querystring')
const getPostData = require('./src/utils/getPostData')

const serveHandle = async (req, res) => {
  res.setHeader('Content-Type', 'application/json')

  //解析url
  const url = req.url
  req.path = url.split('?')[0]
  req.method = req.method.toLowerCase()
  req.query = querystring.parse(url.split('?')[1]) || {}

  // 解析body参数 由于需要监听req.data和req.end事件 所以需要promise进行异步等待
  // 以保证后续的post请求可以获取到body参数
  req.body = await getPostData(req)

  let isBExit = blogRouter(req, res)
  if (isBExit) {
    res.end(JSON.stringify(isBExit))
    return
  }
  let isUserExit = userRouter(req, res)
  if (isUserExit) {
    res.end(JSON.stringify(isUserExit))
    return
  }
  //如果都没有命中 则返回404
  res.writeHead(404, { 'Content-Type': 'text/plain' })
  res.end(
    JSON.stringify({
      error: '404 Not Found',
    })
  )
}

module.exports = serveHandle
